<script setup>
	import { computed, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { FunctionOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'

	const props = defineProps({
		editor: {
			type: Object,
			required: true
		}
	})

	const emit = defineEmits(['function-applied'])

	// 聚合函数分类
	const AGGREGATION_CATEGORIES = [
		{
			key: 'basic',
			label: '基础聚合',
			icon: '📊',
			description: '常用的基础聚合函数'
		},
		{
			key: 'statistical',
			label: '统计函数',
			icon: '📈',
			description: '统计分析相关的聚合函数'
		},
		{
			key: 'window',
			label: '窗口函数',
			icon: '🪟',
			description: '窗口函数和分析函数'
		},
		{
			key: 'string',
			label: '字符串聚合',
			icon: '🔤',
			description: '字符串处理相关的聚合函数'
		}
	]

	// 聚合函数定义
	const AGGREGATION_FUNCTIONS = {
		basic: [
			{
				name: 'COUNT',
				syntax: 'COUNT(*)',
				description: '计算行数，包含NULL值',
				example: 'COUNT(*)',
				params: []
			},
			{
				name: 'COUNT(DISTINCT)',
				syntax: 'COUNT(DISTINCT column)',
				description: '计算不重复值的数量',
				example: 'COUNT(DISTINCT user_id)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'SUM',
				syntax: 'SUM(column)',
				description: '计算数值列的总和',
				example: 'SUM(amount)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'AVG',
				syntax: 'AVG(column)',
				description: '计算数值列的平均值',
				example: 'AVG(score)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'MAX',
				syntax: 'MAX(column)',
				description: '获取列的最大值',
				example: 'MAX(create_time)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'MIN',
				syntax: 'MIN(column)',
				description: '获取列的最小值',
				example: 'MIN(price)',
				params: [{ name: 'column', type: 'column', required: true }]
			}
		],
		statistical: [
			{
				name: 'STDDEV',
				syntax: 'STDDEV(column)',
				description: '计算标准差',
				example: 'STDDEV(score)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'VARIANCE',
				syntax: 'VARIANCE(column)',
				description: '计算方差',
				example: 'VARIANCE(amount)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'MEDIAN',
				syntax: 'PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column)',
				description: '计算中位数',
				example: 'PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary)',
				params: [{ name: 'column', type: 'column', required: true }]
			},
			{
				name: 'PERCENTILE',
				syntax: 'PERCENTILE_CONT(percentile) WITHIN GROUP (ORDER BY column)',
				description: '计算指定百分位数',
				example: 'PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY response_time)',
				params: [
					{ name: 'percentile', type: 'number', required: true, default: '0.95' },
					{ name: 'column', type: 'column', required: true }
				]
			}
		],
		window: [
			{
				name: 'ROW_NUMBER',
				syntax: 'ROW_NUMBER() OVER (ORDER BY column)',
				description: '为每行分配唯一的行号',
				example: 'ROW_NUMBER() OVER (ORDER BY create_time DESC)',
				params: [{ name: 'order_column', type: 'column', required: true }]
			},
			{
				name: 'RANK',
				syntax: 'RANK() OVER (ORDER BY column)',
				description: '计算排名，相同值有相同排名',
				example: 'RANK() OVER (ORDER BY score DESC)',
				params: [{ name: 'order_column', type: 'column', required: true }]
			},
			{
				name: 'DENSE_RANK',
				syntax: 'DENSE_RANK() OVER (ORDER BY column)',
				description: '计算密集排名',
				example: 'DENSE_RANK() OVER (ORDER BY amount DESC)',
				params: [{ name: 'order_column', type: 'column', required: true }]
			},
			{
				name: 'LAG',
				syntax: 'LAG(column, offset) OVER (ORDER BY column)',
				description: '获取前N行的值',
				example: 'LAG(amount, 1) OVER (ORDER BY date)',
				params: [
					{ name: 'column', type: 'column', required: true },
					{ name: 'offset', type: 'number', required: false, default: '1' },
					{ name: 'order_column', type: 'column', required: true }
				]
			},
			{
				name: 'LEAD',
				syntax: 'LEAD(column, offset) OVER (ORDER BY column)',
				description: '获取后N行的值',
				example: 'LEAD(amount, 1) OVER (ORDER BY date)',
				params: [
					{ name: 'column', type: 'column', required: true },
					{ name: 'offset', type: 'number', required: false, default: '1' },
					{ name: 'order_column', type: 'column', required: true }
				]
			},
			{
				name: 'FIRST_VALUE',
				syntax: 'FIRST_VALUE(column) OVER (PARTITION BY column ORDER BY column)',
				description: '获取分组内第一个值',
				example: 'FIRST_VALUE(amount) OVER (PARTITION BY category ORDER BY date)',
				params: [
					{ name: 'value_column', type: 'column', required: true },
					{ name: 'partition_column', type: 'column', required: false },
					{ name: 'order_column', type: 'column', required: true }
				]
			}
		],
		string: [
			{
				name: 'GROUP_CONCAT',
				syntax: 'GROUP_CONCAT(column SEPARATOR separator)',
				description: '将分组内的字符串连接起来',
				example: "GROUP_CONCAT(name SEPARATOR ', ')",
				params: [
					{ name: 'column', type: 'column', required: true },
					{ name: 'separator', type: 'string', required: false, default: ', ' }
				]
			},
			{
				name: 'STRING_AGG',
				syntax: 'STRING_AGG(column, separator)',
				description: '字符串聚合函数（PostgreSQL）',
				example: "STRING_AGG(tag, ', ')",
				params: [
					{ name: 'column', type: 'column', required: true },
					{ name: 'separator', type: 'string', required: false, default: ', ' }
				]
			}
		]
	}

	// 响应式数据
	const selectedCategory = ref('basic')

	// 计算属性
	const currentCategoryFunctions = computed(() => {
		return AGGREGATION_FUNCTIONS[selectedCategory.value] || []
	})

	// 添加聚合函数
	const addAggregation = (func) => {
		if (!props.editor || !props.editor.cminstance) {
			message.warning('编辑器未准备就绪')
			return
		}

		// 生成带占位符的函数文本
		let functionText = func.syntax

		// 为有参数的函数生成占位符版本
		if (func.params && func.params.length > 0) {
			// 替换参数为占位符
			func.params.forEach((param) => {
				const placeholder =
					param.name === 'column'
						? 'column_name'
						: param.name === 'offset'
							? '1'
							: param.name === 'separator'
								? ', '
								: param.name === 'percentile'
									? '0.5'
									: param.name
				functionText = functionText.replace(new RegExp(param.name, 'g'), placeholder)
			})
		}

		// 直接插入函数
		insertFunctionToEditor(functionText)
	}

	// 插入函数到编辑器
	const insertFunctionToEditor = (functionText) => {
		const cm = props.editor.cminstance
		const pos = cm.getCursor()
		cm.replaceRange(functionText, pos)

		// 将光标定位到合适位置
		const newPos = functionText.includes('()')
			? { line: pos.line, ch: pos.ch + functionText.indexOf('()') + 1 }
			: { line: pos.line, ch: pos.ch + functionText.length }

		cm.setCursor(newPos)
		cm.focus()

		emit('function-applied', { function: functionText, position: pos })
		message.success('函数已插入')
	}

	// 获取函数示例
	const getFunctionExample = (func) => {
		return func.example || func.syntax
	}

	// 暴露方法给父组件
	defineExpose({
		addAggregation,
		selectedCategory,
		currentCategoryFunctions
	})
</script>

<template>
	<div class="aggregation-functions">
		<!-- 分类导航 -->
		<div class="category-tabs">
			<a-tabs v-model:activeKey="selectedCategory" size="small" type="card">
				<a-tab-pane v-for="category in AGGREGATION_CATEGORIES" :key="category.key" :tab="category.label">
					<template #tab>
						<span>{{ category.icon }} {{ category.label }}</span>
					</template>
				</a-tab-pane>
			</a-tabs>
		</div>

		<!-- 函数列表 -->
		<div class="function-list">
			<div class="function-header">
				<span class="function-count">共 {{ currentCategoryFunctions.length }} 个函数</span>
			</div>

			<div class="function-items">
				<div
					v-for="func in currentCategoryFunctions"
					:key="func.name"
					class="function-item"
					@click="addAggregation(func)"
				>
					<div class="function-content">
						<div class="function-name">
							<FunctionOutlined class="function-icon" />
							{{ func.name }}
						</div>
						<div class="function-description">{{ func.description }}</div>
						<div class="function-syntax">{{ func.syntax }}</div>
						<div class="function-example">
							<span class="example-label">示例:</span>
							{{ getFunctionExample(func) }}
						</div>
					</div>
					<div class="function-action">
						<a-tooltip title="点击插入函数">
							<InfoCircleOutlined class="info-icon" />
						</a-tooltip>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.aggregation-functions {
		width: 100%;
		max-width: 450px;
	}

	.category-tabs {
		margin-bottom: 12px;
	}

	.function-list {
		max-height: 400px;
		overflow-y: auto;
	}

	.function-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 8px;
	}

	.function-count {
		font-size: 12px;
		color: rgba(0, 0, 0, 0.45);
	}

	.function-items {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.function-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 12px;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		cursor: pointer;
		transition: all 0.3s;
		background: #fff;
	}

	.function-item:hover {
		border-color: #1890ff;
		box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
	}

	.function-content {
		flex: 1;
		min-width: 0;
	}

	.function-name {
		display: flex;
		align-items: center;
		font-weight: 500;
		color: rgba(0, 0, 0, 0.85);
		margin-bottom: 4px;
	}

	.function-icon {
		margin-right: 6px;
		color: #1890ff;
	}

	.function-description {
		font-size: 12px;
		color: rgba(0, 0, 0, 0.65);
		margin-bottom: 6px;
	}

	.function-syntax {
		font-size: 11px;
		color: rgba(0, 0, 0, 0.45);
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		background: #f5f5f5;
		padding: 4px 6px;
		border-radius: 2px;
		margin-bottom: 4px;
	}

	.function-example {
		font-size: 11px;
		color: rgba(0, 0, 0, 0.45);
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
	}

	.example-label {
		color: #1890ff;
		font-weight: 500;
	}

	.function-action {
		margin-left: 8px;
		display: flex;
		align-items: center;
	}

	.info-icon {
		color: rgba(0, 0, 0, 0.45);
		font-size: 14px;
	}

	/* 深色主题适配 */
	@media (prefers-color-scheme: dark) {
		.function-item {
			background: #1f1f1f;
			border-color: #434343;
		}

		.function-item:hover {
			border-color: #1890ff;
			background: #111b26;
		}

		.function-syntax {
			background: #2d2d2d;
			color: #e6e6e6;
		}
	}
</style>
